package PreHr

import (
	"ali-hr/Database"
	"ali-hr/Models"
)

/**
 * Created by Goland
 * User: wkk alisleepy@hotmail.com
 * Time: 2021/12/21 - 00:50
 * Desc: <预入职系统员工相关业务>
 */

// PreStaffList 预入职员工列表
func PreStaffList(pageIndex int, pageSize int, filters map[string]any, all bool) ([]Models.PreStaff, int, error) {
	// 获取所有的预入职员工信息
	var preStaffs []Models.PreStaff
	var total int
	var Db = Database.SqlDB

	// 查询条件
	for key, val := range filters {
		if val == "" || val == 0 || val == nil {
			continue
		}
		if key == "name" {
			Db = Db.Where("name LIKE ?", "%"+val.(string)+"%")
		}
		if key == "department_id" {
			Db = Db.Where("department_id = ?", val)
		}
		if key == "status" {
			Db = Db.Where("status = ?", val)
		}
		if key == "mobile" {
			Db = Db.Where("mobile = ?", val)
		}
		if key == "join_date" {
			Db = Db.Where("join_date = ?", val)
		}
	}

	// 是否获取所有
	if all {
		err1 := Db.Preload("Department").Find(&preStaffs).Error
		if err1 != nil {
			return nil, 0, err1
		}
		Db.Table(Models.DepartmentTableName).Count(&total)
		return preStaffs, total, nil
	}

	//  获取分页数据
	err2 := Db.Preload("Department").Limit(pageSize).Offset((pageIndex - 1) * pageSize).Find(&preStaffs).Error
	if err2 != nil {
		return nil, 0, err2
	}
	Db.Table(Models.PreStaffTableName).Count(&total)
	return preStaffs, total, nil
}

// GetPreStaff 获取员工预入职信息
func GetPreStaff(filters map[string]any) (Models.PreStaff, error) {
	var preStaff Models.PreStaff
	Db := Database.SqlDB

	// 查询条件
	for key, val := range filters {
		if val == 0 || val == "" || val == nil {
			continue
		}
		if key == "id" {
			Db = Db.Where("id = ?", val)
		}
		if key == "id_card" {
			Db = Db.Where("id_card = ?", val)
		}
	}

	err := Db.Preload("Department").Find(&preStaff).Error
	if err != nil {
		return preStaff, err
	}

	return preStaff, nil
}

// UpdatePreStaff 修改预入职员工信息
func UpdatePreStaff() {

}

// Entry StaffEntry 员工入职操作
func Entry() {

}

// CancelEntry 取消员工入职操作
func CancelEntry(postData map[string]any) (error, string) {
	var preStaff Models.PreStaff

	err := Database.SqlDB.Where("id = ?", postData["id"]).Find(&preStaff).Error
	if err != nil {
		return err, "获取预入职员工信息失败"
	}

	// 更新操作
	err2 := Database.SqlDB.Model(&preStaff).Update(postData).Error
	if err2 != nil {
		return err2, "更新预入职员工信息失败"
	}

	return nil, "取消入职操作成功"
}
